package com.setup.trac.controller;

import java.math.BigDecimal;
import java.util.Date;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.validation.BindException;
import org.springframework.web.bind.ServletRequestDataBinder;
import org.springframework.web.multipart.support.ByteArrayMultipartFileEditor;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.SimpleFormController;

import com.setup.trac.dao.DAOService;
import com.setup.trac.pojo.Allegati;
import com.setup.trac.pojo.Progetti;
import com.setup.trac.pojo.StoricoTicket;
import com.setup.trac.pojo.Tickets;
import com.setup.trac.pojo.condition.AllegatiFinderByIdStorico;
import com.setup.trac.pojo.condition.AllegatiFinderBySessioneUtenteWeb;
import com.setup.trac.pojo.condition.StoricoTicketFinderByIdStorico;
import com.setup.trac.pojo.wrappers.StatiView;
import com.setup.trac.pojo.wrappers.TicketView;
import com.setup.trac.pojo.wrappers.UtentiView;
import com.setup.trac.service.ManageTicketService;
import com.setup.trac.service.SearchService;
import com.setup.trac.util.StatoConstant;
import com.setup.trac.web.form.TicketForm;

public class ModificaTicketController extends SimpleFormController {

	private SearchService searchService;
	private DAOService daoService;
	private ManageTicketService manageTicketService;
	private String onCloseTicketView;

	@Override
	protected ModelAndView onSubmit(HttpServletRequest request,
			HttpServletResponse response, Object command, BindException errors)
			throws Exception {
		TicketForm tf = (TicketForm) command;
		Date  modifyDate = new Date();
		Tickets t = getSearchService().find(new Tickets[0],
				new TicketFinderByIdTicket(tf.getIdTicket()), Tickets.class)[0];
		t.setDataUltimaModifica(new Date());
		UtentiView utenteLoggato = (UtentiView) request.getSession(false).getAttribute("loginForm");
	
		t.setUtentiByIdUtenteUltimaModifica(utenteLoggato.getUtenti());
		StoricoTicket st = searchService.find(new StoricoTicket[0], new StoricoTicketFinderByIdStorico(request.getParameter("idStorico")) , StoricoTicket.class)[0];

//		TicketView[] ticketViews = findTicketById(idTicket);
//		t = ticketViews[0].getTickets();

		st.setDataModifica(modifyDate);
		st.setDescrizione(request.getParameter("descrizione"));

		if (utenteLoggato.getUtenti().getProfilo().getDescrizione()
				.equalsIgnoreCase("DEVELOPER")) {
			st.setFatturare(Boolean.valueOf(tf.isDaFatturare()));
			String idOwner = request.getParameter("idOwner");
			String idUtenteAssegnatario = request
					.getParameter("idUtenteAssegnatario");
			idOwner = (idUtenteAssegnatario != null || !"-1"
					.equals(idUtenteAssegnatario)) ? idUtenteAssegnatario
					: idOwner;
			if (null != idOwner && !"".equals(idOwner)) {
				t.setUtentiByIdOwner(getSearchService().findUtenteById(
						idOwner));
			}
			if (tf.getGiorniConsuntivati() != null
					&& !"".equals(tf.getGiorniConsuntivati())) {
				st.setGiorniConsuntivo(tf.getGiorniConsuntivati());
			}
			if (tf.getGiorniPrevisti() != null
					&& !"".equals(tf.getGiorniPrevisti())) {
				st.setGiorniPrevisti(tf.getGiorniPrevisti());
			}
			if (tf.getOreConsuntivate() != null
					&& !"".equals(tf.getOreConsuntivate())) {
				st.setOreConsuntivo(tf.getOreConsuntivate());
			}
			if (tf.getOrePreviste() != null
					&& !"".equals(tf.getOrePreviste())) {
				st.setOrePreviste(tf.getOrePreviste());
			}
			st.setProssimaAzione(tf.getProssimaAzione());
			st.setUtenti(utenteLoggato.getUtenti());
			StatiView sv = new StatiView();
			sv.getStati().setIdStato(
					new BigDecimal(request.getParameter("idStato")));
			t.setStati(sv.getStati());
		}
		t.setDataUltimaModifica(modifyDate);
		t.setUtentiByIdUtenteUltimaModifica(utenteLoggato.getUtenti());
		st.setTickets(t);
		st.setUtenti(((UtentiView) request.getSession().getAttribute(
				"loginForm")).getUtenti());
		TicketView ticketView = new TicketView();
		ticketView.setTickets(t);
		st = manageTicketService.updateTicket(ticketView, st,false);
		// inserimento di un nuovo record su storico tickets e update su
		// tickets

	
		Allegati[] allegati = getSearchService()
		.find(
				new Allegati[0],
				new AllegatiFinderBySessioneUtenteWeb(request.getSession(false).getId()), Allegati.class);
		st.setDescrizione(tf.getDescrizione());
		for (int i = 0; i < allegati.length; i++) {
			Allegati a = allegati[i];
			if(a.getStoricoTicket()==null){
				a.setStoricoTicket(st);
				a.setTickets(t);
				a.setTemporaneo(false);
				a.setSessioneUtente(null);
				getManageTicketService().updateAllegato(a);
			}
		}
		ModelAndView mv = null;
		if ((request.getParameter("idStato") != null && !"".equals(request
				.getParameter("idStato")))
				&& new BigDecimal(request.getParameter("idStato"))
						.intValue() == StatoConstant.CHIUSO.getIdStato()
						.intValue()) {
			request.setAttribute("idTicket", t.getIdTicket());
			mv = new ModelAndView(getOnCloseTicketView() + "?idTicket="
					+ t.getIdTicket());
			request.getSession(false).setAttribute("ticketClosed", t);
		}else{
			mv= new ModelAndView(getSuccessView());
			request.getSession().setAttribute("nextPage", "/search.do");
		}
		return mv;
	}

	public String getOnCloseTicketView() {
		return this.onCloseTicketView;
	}

	@Override
	protected ModelAndView showForm(HttpServletRequest request,
			HttpServletResponse response, BindException errors, Map controlModel)
			throws Exception {
		request.setAttribute("action", "modificaTicket.do");
		return super.showForm(request, response, errors, controlModel);
	}

	@Override
	protected Object formBackingObject(HttpServletRequest request)
			throws Exception {
		Tickets[] ticket = searchService.find(new Tickets[0],
				new TicketFinderByIdTicket(request.getParameter("idTicket")),
				Tickets.class);
		Set<StoricoTicket> storicos = ticket[0].getStoricoTickets();
		StoricoTicket st = null;
		Iterator<StoricoTicket> itStoricos = storicos.iterator();
		while (itStoricos.hasNext()) {
			st = itStoricos.next();
			if (st.getIdStorico().toPlainString().equals(
					request.getParameter("idStorico"))) {
				break;
			}

		}
		TicketForm tf = new TicketForm();
		tf.setDescrizione(st.getDescrizione());
		tf.setIdTicket(ticket[0].getIdTicket().toPlainString());
		if(st.getProssimaAzione()!=null){
			tf.setProssimaAzione(st.getProssimaAzione());
		}
		Progetti p = searchService.findProgettoById(ticket[0].getIdProgetto()
				.toPlainString());
		tf.setDescrizioneProgetto(p.getDescrizione());
		tf.setIdProgetto(p.getIdProgetto().toPlainString());
		if (ticket[0].getUtentiByIdOwner() != null) {
			tf.setIdOwner(ticket[0].getUtentiByIdOwner().getIdUtente()
					.toPlainString());
		}
		tf.setDescrizione(st.getDescrizione());
		tf.setOreConsuntivate(st.getOreConsuntivo());
		tf.setOrePreviste(st.getOrePreviste());
		
		tf.setTitoloTicket(ticket[0].getTitoloTicket());

		request.setAttribute("idStato", ticket[0].getStati().getIdStato());
		UtentiView utenteLoggato = (UtentiView) request.getSession(false)
				.getAttribute("loginForm");
		tf.setIdUtente(utenteLoggato.getUtenti().getIdUtente().toPlainString());
		request.setAttribute("action", "modificaTicket.do");
		if (utenteLoggato.getUtenti().getProfilo().getDescrizione().equals(
				"DEVELOPER")) {

			if (ticket[0].getUtentiByIdOwner() != null) {
				request.setAttribute("owner", ticket[0].getUtentiByIdOwner());
			}
		}
		Allegati[] allegati = getSearchService()
				.find(
						new Allegati[0],
						new AllegatiFinderByIdStorico(st.getIdStorico()
								.toPlainString()), Allegati.class);
		for (int i = 0; i < allegati.length; i++) {
			Allegati a = allegati[i];
			a.setSessioneUtente(request.getSession(false).getId());
			a.setTemporaneo(true);

			getManageTicketService().updateAllegato(a);
		}

		return tf;
	}

	public SearchService getSearchService() {
		return searchService;
	}

	public void setSearchService(SearchService searchService) {
		this.searchService = searchService;
	}

	public DAOService getDaoService() {
		return daoService;
	}

	public void setDaoService(DAOService daoService) {
		this.daoService = daoService;
	}

	@Override
	protected void initBinder(HttpServletRequest request,
			ServletRequestDataBinder binder) throws Exception {
		binder.registerCustomEditor(byte[].class,
				new ByteArrayMultipartFileEditor());
	}

	public ManageTicketService getManageTicketService() {
		return manageTicketService;
	}

	public void setManageTicketService(ManageTicketService manageTicketService) {
		this.manageTicketService = manageTicketService;
	}

	public void setOnCloseTicketView(String onCloseTicketView) {
		this.onCloseTicketView = onCloseTicketView;
	}
}
